package com.sduept.nwld.mobile.rest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.manager.document.DocumentDirManager;
import com.sduept.nwld.dataserver.manager.rota.RotaManager;
import com.sduept.nwld.dataserver.manager.rota.RotaPersonManager;
import com.sduept.nwld.dataserver.model.AppDocument;
import com.sduept.nwld.dataserver.model.rota.HolidayInfo;
import com.sduept.nwld.dataserver.model.rota.RotaLocation;
import com.sduept.nwld.dataserver.model.rota.RotaOrder;
import com.sduept.nwld.dataserver.model.rota.RotaPerson;
import com.sduept.nwld.mobile.manager.MobileUtil;
import com.sduept.permission.manager.DepartManager;
import com.sduept.utils.Base64;
import com.sduept.utils.DateUtil;

/**
 * 员工值班情况Rest接口
 * @author leodexin & zhouhuiting
 *
 */
@RestController
@RequestMapping("/userduty/")
public class UserDutyService {
	@Autowired
	private SuperDAO dao;
	@Autowired
	private RotaManager rotaManager;
	@Autowired
	private RotaPersonManager rotaPersonManager;
	@Autowired
	private DepartManager dm;
	@Autowired
	private DocumentDirManager docManager;
	//SQL注入检测类
	@Inject
	private MobileUtil mobileUtil;
	@Autowired
	private CommonDocumentProperties pros;
	
	/**
	 * 根据年份获取一年的值班信息，包含假期和周末值班情况，以及这一年的所有假期
	 * @param year
	 * @return {holidays:[HolidayInfo],info:[RotaPerson]}
	 */

	@GetMapping("/getDutyInfo/{year}")
	public String getDutyInfo(@PathVariable("year") int year) {
		try {
			year = Integer.parseInt(mobileUtil.SQLInjectCheck(String.valueOf(year)));
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		JSONObject jso = new JSONObject();
		List<RotaPerson> persons = rotaManager.findRotaPersonByYear(year);
		List<HolidayInfo> holidays = rotaManager.findHolidaysByYear(year);
		jso.put("holidays", holidays);
		jso.put("info", persons);
		return jso.toJSONString();
	}
	
	
	/**
	 * 获取今年的节假日值班信息（不包含周末）
	 * @return {type:[[name,time]]}
	 * */

	@GetMapping("/getHolidayDutyInfo/{year}")
	public String getHolidayDutyInfo(@PathVariable("year") int year) {
		try {
			year = Integer.parseInt(mobileUtil.SQLInjectCheck(String.valueOf(year)));
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		JSONObject jso = new JSONObject();
		List<RotaPerson> persons = rotaManager.findRotaPersonByYear(year);
		List<HolidayInfo> holidays = rotaManager.findHolidaysByYear(year);
		List<String> holidayNames = new ArrayList<>();
		Map<String, List<RotaPerson>> holidayDutyInfos = new HashMap<>();
		for (HolidayInfo holidayInfo : holidays) {
			if (!holidayNames.contains(holidayInfo.getHolidayName())) {
				holidayNames.add(holidayInfo.getHolidayName());
			}
			List<RotaPerson> rotaInfos = holidayDutyInfos.get(holidayInfo
					.getHolidayName());
			if (rotaInfos == null) {
				rotaInfos = new ArrayList<>();
				holidayDutyInfos.put(holidayInfo.getHolidayName(), rotaInfos);
			}
			RotaPerson person = null;
			for (RotaPerson p : persons) {
				if (p.getRotaDate().getTime() == holidayInfo.getHoliday()
						.getTime()) {
					person = p;
				}
			}
			if (person == null) {
				person = new RotaPerson();
				person.setRotaDate(holidayInfo.getHoliday());
			}
			rotaInfos.add(person);
		}
		jso.put("holidays", holidayNames);
		jso.put("info", holidayDutyInfos);
		return jso.toString();
	}

	/**
	 * 根据日期获取节假日人员去向
	 * 
	 * @param time
	 * @return [[name,time]]
	 * */

	@GetMapping("/getHolidayDutyPositionByDate/{date}")
	public String getHolidayDutyPositionByDate(@PathVariable("date") String date) {
			try {
				date = mobileUtil.SQLInjectCheck(String.valueOf(date));
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		try {
			Date rd = DateUtil.getDateByString(date, DateUtil.pattern_ymd);
			List<RotaLocation> rotaInfos = rotaManager
					.findRotaLocationByDate(rd);
			if (rotaInfos != null && !rotaInfos.isEmpty())
				return JSONArray.toJSONString(rotaInfos);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return "";
	}

	/**
	 * 根据节日获取人员去向
	 * 
	 * @param holidayName
	 *            ,year
	 * @return info:{name:{time:position}}
	 * */

	@GetMapping("/getHolidayDutyPositionByType/{holidayName}/{year}")
	public String getHolidayDutyPositionByType(
			@PathVariable("holidayName") String holidayName,
			@PathVariable("year") int year) {
		try {
			holidayName = mobileUtil.SQLInjectCheck(String.valueOf(holidayName));
			year = Integer.parseInt(mobileUtil.SQLInjectCheck(String.valueOf(year)));
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		JSONObject jso = new JSONObject();
		List<HolidayInfo> holidays = rotaManager.findHolidaysByName(
				holidayName, year);
		List<String> dates = new ArrayList<>();
		List<RotaLocation> rotaLocations = rotaManager
				.findLocationsByDates(holidays);
		Map<String, Map<String, String>> holidayDutyInfos = new HashMap<>();
		for (HolidayInfo holidayInfo : holidays) {
			dates.add(DateUtil.getStringDate(holidayInfo.getHoliday(),
					DateUtil.pattern_ymd));
		}
		for (RotaLocation l : rotaLocations) {
			Map<String, String> locations = holidayDutyInfos.get(l
					.getPersonName());
			if (locations == null) {
				locations = new HashMap<>();
				holidayDutyInfos.put(l.getPersonName(), locations);
			}
			locations.put(DateUtil.getStringDate(l.getHoliday(),
					DateUtil.pattern_ymd), l.getLocation());
		}
		jso.put("dates", dates);
		jso.put("info", holidayDutyInfos);
		return jso.toString();
	}

	/**
	 * 获取保护处所有人员的名单
	 * 
	 * @param
	 * @return {nameCode:name,nameCode:name}
	 * */
	//TODO 配置系统参数后处理

	@GetMapping("/getAllPeople")
	public String getAllPeople() {
		Map<String, String> map = new HashMap<>();
		/*List<PersonnelEntityBean> peoples = dm
				.findDeptPersonnels("5915851ea349462f78a1130e");
		for (PersonnelEntityBean p : peoples) {
			if (p.getCode() != null && p.getName() != null) {
				map.put(p.getCode(), p.getName());
			}
		}*/
		List<RotaOrder> peoples=dao.findAll(RotaOrder.class);
		for (RotaOrder p : peoples) {
			if (p.getPersonId() != null && p.getPersonName() != null) {
				map.put(p.getPersonId(), p.getPersonName());
			}
		}
		return JSONObject.toJSONString(map);
	}

	/**
	 * 编辑去向
	 * 
	 * @param time
	 *            ,name,position
	 * @return {type:[[name,time]]}
	 * */

	@GetMapping("/editPosition/{nameCode}/{name}/{date}/{position}/{year}")
	public String editPosition(@PathVariable("nameCode") String nameCode,
			@PathVariable("name") String name,@PathVariable("date") String date,
			@PathVariable("position") String position,@PathVariable("year") int year) {
		try {
			nameCode = mobileUtil.SQLInjectCheck(String.valueOf(nameCode));
			name = mobileUtil.SQLInjectCheck(String.valueOf(name));
			date = mobileUtil.SQLInjectCheck(String.valueOf(date));
			position = mobileUtil.SQLInjectCheck(String.valueOf(position));
			year = Integer.parseInt(mobileUtil.SQLInjectCheck(String.valueOf(year)));
		} catch (Exception e) {
			e.printStackTrace();
			return "ERROR";
		}
		Date rd = DateUtil.getDateByString(date, DateUtil.pattern_ymd);
		//List<HolidayInfo> holidays = rotaManager.findHolidaysByYear(year);
		RotaLocation info = rotaManager.findRotaLocationByDate(rd, name);
		if (info == null)
			info = new RotaLocation();
		info.setPersonId(nameCode);
		info.setPersonName(name);
		info.setLocation(position);
		info.setHoliday(rd);
		info.setYear(year);
		try {
			rotaManager.updateRotaLocation(info);
		} catch (Exception e) {
			return "ERROR";
		}
		return "SUCCESS";
	}

	/**
	 * 修改值班人
	 * 
	 * @param time
	 *            ,name
	 * @return {type:[[name,time]]}
	 * */

	@GetMapping("/editDutyPeople/{nameCode}/{name}/{date}/{year}")
	public String editDutyPeople(@PathVariable("nameCode") String nameCode,
			@PathVariable("name") String name,@PathVariable("date") String date,@PathVariable("year") int year) {
			try {
				nameCode = mobileUtil.SQLInjectCheck(String.valueOf(nameCode));
				name =mobileUtil.SQLInjectCheck(String.valueOf(name));
				date = mobileUtil.SQLInjectCheck(String.valueOf(date));
				year = Integer.parseInt(mobileUtil.SQLInjectCheck(String.valueOf(year)));
			} catch (Exception e) {
				e.printStackTrace();
				return "ERROR";
			}
		Date rd = DateUtil.getDateByString(date, DateUtil.pattern_ymd);
		//List<HolidayInfo> holidays = rotaManager.findHolidaysByYear(year);
		RotaPerson info = rotaManager.getRotaPerson(rd);
		if (info == null)
			info = new RotaPerson();
		info.setPersonId(nameCode);
		info.setPersonName(name);
		info.setRotaDate(rd);
		info.setYear(year);
		try {
			rotaManager.updateRotaPerson(info);
		} catch (Exception e) {
			return "ERROR";
		}
		return "SUCCESS";
	}

	/**
	 * 获取节假日对应的日期
	 * 
	 * @param year
	 * @return {holidayName:[date1,date2]}
	 * */

	@GetMapping("/getHolidaysWithDate/{year}")
	public String getHolidaysWithDate(@PathVariable("year") int year) {
			try {
				year = Integer.parseInt(mobileUtil.SQLInjectCheck(String.valueOf(year)));
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		Map<String, List<String>> holidays = new HashMap<>();
		List<HolidayInfo> holidayInfos = rotaManager.findHolidaysByYear(year);
		for (HolidayInfo h : holidayInfos) {
			List<String> holiday = holidays.get(h.getHolidayName());
			if (holiday == null) {
				holiday = new ArrayList<>();
				holidays.put(h.getHolidayName(), holiday);
			}
			holiday.add(DateUtil.getStringDate(h.getHoliday(),
					DateUtil.pattern_ymd));
		}
		return JSONObject.toJSONString(holidays);
	}

	/**
	 * 获取某个月的周末值班信息
	 * 
	 * @return
	 * */

	@GetMapping("/getWeekendDutyPersonByMonth/{date}")
	public String getWeekendDutyPersonByMonth(@PathVariable("date") String date) {
			try {
				date = mobileUtil.SQLInjectCheck(String.valueOf(date));
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
//		int year = Integer.parseInt(date.split("-")[0]);
//		int month = Integer.parseInt(date.split("-")[1]);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(DateUtil.getDateByString(date+"-01", DateUtil.pattern_ymd));
		int year=calendar.get(Calendar.YEAR);
		int month=calendar.get(Calendar.MONTH)+1;
		List<RotaPerson> rotaPersons = rotaPersonManager.findRotaPersonByMonth(
				year, month);
		if(rotaPersons!=null){
			return JSONArray.toJSONString(rotaPersons);
		}
		return "";
	}

	/**
	 * 获取某个周六或者周天值班信息
	 * 
	 * @return
	 * */

	@GetMapping("/getWeekendDutyPersonByDate/{date}")
	public String getWeekendDutyPersonByDate(@PathVariable("date") String date) {
			try {
				date = mobileUtil.SQLInjectCheck(String.valueOf(date));
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		List<RotaPerson> rotaPersons = rotaPersonManager
				.findRotaPersonByRoteDate(DateUtil.getDateByString(date,
						DateUtil.pattern_ymd));
		if (rotaPersons.size() > 0) {
			return JSONObject.toJSONString(rotaPersons.get(0));
		}
		return "";
	}

	/**
	 * 修改某个周六或者周天值班信息
	 * 
	 * @return
	 * */

	@GetMapping("/editWeekendDutyPersonByDate/{date}/{personName}/{nameCode}")
	public String editWeekendDutyPersonByDate(@PathVariable("date") String date,
			@PathVariable("personName") String personName,
			@PathVariable("nameCode") String nameCode) {
			try {
				date = mobileUtil.SQLInjectCheck(String.valueOf(date));
				personName = mobileUtil.SQLInjectCheck(String.valueOf(personName));
				nameCode = mobileUtil.SQLInjectCheck(String.valueOf(nameCode));
			} catch (Exception e) {
				e.printStackTrace();
				return "ERROR";
			}
		Date rd = DateUtil.getDateByString(date, DateUtil.pattern_ymd);
		RotaPerson info = rotaManager.getRotaPerson(rd);
		info.setPersonName(personName);
		info.setPersonId(nameCode);
		try {
			rotaPersonManager.updateRotaPerson(info);
		} catch (Exception e) {
			return "ERROR";
		}
		return "SUCCESS";
	}

	/**
	 * 获取值班常用信息
	 * 
	 * @return
	 * */

	@GetMapping("/getDutyCommonUseInfo")
	public String getDutyCommonUseInfo() {
		try {
			List<AppDocument> docs = docManager
					.getDocumentByDirName("值班常用信息",null);
			if (docs != null && !docs.isEmpty())
				return JSONArray.toJSONString(docs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
 
	/**
	 * 下载值班常用信息及要求文档附件
	 * 
	 * @return
	 * */
	//TODO 手机端更新版本后才能删除，使用fileService中的接口

	@GetMapping("/downLoadDutyCommonUseInfo/{rotaFileId}")
	public String downLoadDutyCommonUseInfo(
			@PathVariable("rotaFileId") String rotaFileId) {
		try {
			rotaFileId = mobileUtil.SQLInjectCheck(rotaFileId);
		} catch (Exception e) {
			e.printStackTrace();
			return "查找文件失败，无法下载";
		}
		String res = null;
		if (!"null".equals(rotaFileId)) {
			AppDocument rd = docManager.findAppDocumentById(rotaFileId);
			if (rd != null) {// id在数据库中有
				// 需要优化
				String filePath =pros.getExportTempPath()+rd.getPath();
				try {
					res = Base64.encodeFromFile(filePath);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				res = "查找文件失败，无法下载";
			}
		}
		return res;
	}
	
}
